package org.dtrd.modules.quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.CheckUtil;
import org.dtrd.modules.patient.service.impl.DtrdEntRdPatientServiceImpl;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwClientInfoResponse;
import org.dtrd.modules.system.entity.bean.qiyeweixin.QwFollowUser;
import org.dtrd.modules.system.service.impl.DtrdEntRdQwClientFollowServiceImpl;
import org.dtrd.modules.system.service.impl.DtrdEntRdQwClientServiceImpl;
import org.dtrd.modules.system.service.impl.ThirdAppWechatEnterpriseServiceImpl;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 企业微信同步
 *
 * @author 萧
 * @date:2021-11-09 10:04 下午
 **/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class QwClientSyncJob implements Job {

    @Autowired
    private ThirdAppWechatEnterpriseServiceImpl wechatEnterpriseServiceImpl;

    @Autowired
    private DtrdEntRdPatientServiceImpl patientService;


    @Autowired
    private DtrdEntRdQwClientServiceImpl clientService;

    @Autowired
    private DtrdEntRdQwClientFollowServiceImpl clientFollowService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 获取配置了客户联系功能的成员列表
        List<String> followUserList = wechatEnterpriseServiceImpl.getFollowUserList();
        log.info("QwClientSyncJob.execute.[context] 成员列表 " + followUserList);
        if (CheckUtil.isNotEmpty(followUserList)) {
            // 根据成员查询客户列表
            followUserList.stream().map(userId -> {
                List<String> clientList = wechatEnterpriseServiceImpl.getClientList(userId);
                log.info("QwClientSyncJob.execute.[context] 根据成员查询客户列表 userId=" + userId + "; clientList=" + clientList);
                return clientList;
            })
                    .filter(CheckUtil::isNotEmpty)
                    .flatMap(Collection::stream)
                    .map(clientId -> {
                        QwClientInfoResponse clientDetail = wechatEnterpriseServiceImpl.getClientDetail(clientId);
                        log.info("QwClientSyncJob.execute.[context] 查询客户详情 clientId= " + clientId + ";clientDetail=" + clientDetail);
                        return clientDetail;
                    })
                    .filter(Objects::nonNull).forEach(res -> {
                List<QwFollowUser> follow_user = res.getFollow_user();
                log.info("QwClientSyncJob.execute.[context] 客户详情：" + res.getExternal_contact() + "; 跟进员工  " + follow_user);
                Integer patientId = null;
                String mobile = null;
                if (CheckUtil.isNotEmpty(follow_user)) {
                    //保存跟进信息
                    clientFollowService.saveExternalFollowUser(follow_user,res.getExternal_contact().getExternal_userid());
                    // 同步处理用户表记录
                    List<String> remark_mobiles = follow_user.get(0).getRemark_mobiles();
                    mobile = Optional.ofNullable(remark_mobiles).filter(CheckUtil::isNotEmpty).map(rmobile -> rmobile.get(0)).orElse(null);
                    log.info("QwClientSyncJob.execute.[context] remark_mobiles=" + remark_mobiles);
                    if (CheckUtil.isNotEmpty(mobile)) {
                        log.info("QwClientSyncJob.execute.[context] mobile=" + mobile);
                        patientId = patientService.syncQwClientInfo(res.getExternal_contact(), mobile);
                    }
                }
                // 保存企业微信客户信息
                clientService.saveExternalContact(res.getExternal_contact(), patientId, mobile);
            });
        } else {
            log.info("QwClientSyncJob.execute.[context] 成员列表为空 ，无需处理");
        }
    }
}
